

import { delEmilList, getEmilList, searchEmilList } from '@/services';
import { IEmilItem } from '@/types/modules/emil';
import { Effect, Reducer } from 'umi';

export interface EmilStateType {
    EmilList: IEmilItem[],
    EmilLength: number
}

export interface EmilModelType {
    namespace: 'emil';
    state: EmilStateType;
    effects: {
        getEmilList: Effect;
        delEmilList: Effect;
        searchEmilList:Effect;
    };
    reducers: {
        save: Reducer<EmilModelType>;
        // 启用 immer 之后
        // save: ImmerReducer<viewModelState>;
    }
}

const EmilModel: EmilModelType = {
    // namespace： 命名空间 数据模型，限定模块之间不相互影响 
    namespace: 'emil',
    // state：数据模型状态，相当于vuex的state
    state: {
        EmilList: [],
        EmilLength: 0
    },
    // effects：异步操作，相当于vuex的action
    effects: {
        // * 相当于async, yield 相当于await

        // 获取邮件列表
        *getEmilList({ payload }, { call, put }) {
            let result = yield call(getEmilList, payload)
            if (result.data) {
                yield put({
                    type: "save",
                    payload: {
                        EmilList: result.data[0],
                        EmilLength: result.data[1]
                    }
                })
            }
        },
         // 搜索邮箱列表
         *searchEmilList({ payload }, { call, put }) {
            const { page, inp0, inp1, inp2 } = payload 
            let result = yield call(searchEmilList, page, inp0, inp1, inp2)
            if (result.data) {
                yield put({
                    type: "save",
                    payload: {
                        EmilList: result.data[0],
                        EmilLength: result.data[1]
                    }
                })
            }

        },
        // 删除数据
        *delEmilList({ payload }, { call, put }) {
            let result = yield call(delEmilList, payload)
            if (result.statusCode == 200) {
                let results = yield call(getEmilList, payload)
                if (results.data) {
                    yield put({
                        type: "save",
                        payload: {
                            EmilList: results.data[0],
                            EmilLength: results.data[1]
                        }
                    })
                }
            }
        },
    },
    // reducers：同步操作，相当于vuex的mutation
    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        }
    },
};

export default EmilModel;